import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { padLeft, range } from '../utility'

class MonthPicker extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      isToggle: false,
      selectedYear: this.props.year,
    }
  }

  componentDidMount() {
    document.addEventListener('click', this.handleClick, false)
  }
  componentWillUnmount() {
    document.removeEventListener('click', this.handleClick, false)
  }
  handleClick = (e) => {
    if (this.node.contains(e.target)) return
    this.setState({
      isToggle: false
    })
  }
  handleToggle = (e) => {
    e.preventDefault()

    this.setState({
      isToggle: !this.state.isToggle
    })
  }

  getActive = (v, cur) => {
    return v === cur ? "dropdown-item active text-white" : "dropdown-item"
  }

  handleChangeYear = (e, yearNum) => {
    e.preventDefault()
    this.setState({
      selectedYear: yearNum
    })
  }

  handleChangeMonth = (e, monthNum) => {
    e.preventDefault()
    this.setState({
      isToggle: false
    })
    this.props.onChange(this.state.selectedYear, monthNum)
  }

  render() {
    const { year, month } = this.props
    const { isToggle, selectedYear } = this.state
    const monthRange = range(12, 1)
    const yearRange = range(9, -4).map(number => number + year)

    return (
      <div className="dropdown month-picker-component" ref={ref => { this.node = ref }}>
        <p>选择月份</p>
        <button
          className="btn btn-lg btn-secondary dropdown-toggle"
          onClick={this.handleToggle}
        >
          {`${year}年 ${padLeft(month)}月`}
        </button>

        {isToggle &&
          <div className="dropdown-menu" style={{ display: 'block' }}>
            <div className="row">
              <div className="col border-right years-range">
                {yearRange.map((yearNum, index) => (
                  <a key={index}
                    href="#"
                    className={this.getActive(yearNum, selectedYear)}
                    onClick={(e) => { this.handleChangeYear(e, yearNum) }}
                  >
                    {yearNum} 年
                  </a>
                ))}
              </div>
              <div className="col months-range">
                {monthRange.map((monthNum, index) => (
                  <a key={index}
                    href="#"
                    className={this.getActive(monthNum, month)}
                    onClick={(e) => { this.handleChangeMonth(e, monthNum) }}
                  >
                    {padLeft(monthNum)} 月
                  </a>
                ))}
              </div>
            </div>
          </div>
        }
      </div>
    )
  }
}

MonthPicker.propTypes = {
  year: PropTypes.number.isRequired,
  month: PropTypes.number.isRequired,
  onChange: PropTypes.func.isRequired,
}
export default MonthPicker